<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css" integrity="sha256-dABdfBfUoC8vJUBOwGVdm8L9qlMWaHTIfXt+7GnZCIo=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.csgrandeur.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.22.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":"default"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="前缀和、差分 前缀和与差分作为互补技术，分别通过预处理和逆运算高效处理数组的区间查询与批量修改问题。">
<meta property="og:type" content="article">
<meta property="og:title" content="16.前缀和、差分">
<meta property="og:url" content="http://blog.csgrandeur.cn/2025-04-02-16-%E5%89%8D%E7%BC%80%E5%92%8C%E3%80%81%E5%B7%AE%E5%88%86/index.html">
<meta property="og:site_name" content="CSGrandeur&#39;s Thinking">
<meta property="og:description" content="前缀和、差分 前缀和与差分作为互补技术，分别通过预处理和逆运算高效处理数组的区间查询与批量修改问题。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2025-04-02T03:08:59.000Z">
<meta property="article:modified_time" content="2025-04-03T10:28:46.716Z">
<meta property="article:author" content="CSGrandeur">
<meta property="article:tag" content="ACM">
<meta property="article:tag" content="Algorithm">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://blog.csgrandeur.cn/2025-04-02-16-%E5%89%8D%E7%BC%80%E5%92%8C%E3%80%81%E5%B7%AE%E5%88%86/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.csgrandeur.cn/2025-04-02-16-%E5%89%8D%E7%BC%80%E5%92%8C%E3%80%81%E5%B7%AE%E5%88%86/","path":"2025-04-02-16-前缀和、差分/","title":"16.前缀和、差分"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>16.前缀和、差分 | CSGrandeur's Thinking</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?7958adf931092425a489778560129144"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">CSGrandeur's Thinking</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">Cogito Ergo Sum</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E7%BC%80%E5%92%8C%E5%B7%AE%E5%88%86"><span class="nav-number">1.</span> <span class="nav-text">前缀和、差分</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E7%BC%80%E5%92%8C"><span class="nav-number">1.1.</span> <span class="nav-text">前缀和</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E5%8C%BA%E9%97%B4%E5%92%8C"><span class="nav-number">1.1.1.</span> <span class="nav-text">例：区间和</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E6%9C%80%E5%A4%A7%E5%8A%A0%E6%9D%83%E7%9F%A9%E5%BD%A2"><span class="nav-number">1.1.2.</span> <span class="nav-text">例：最大加权矩形</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B7%AE%E5%88%86"><span class="nav-number">1.2.</span> <span class="nav-text">差分</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E5%8C%BA%E9%97%B4%E5%8F%98%E5%8C%96"><span class="nav-number">1.2.1.</span> <span class="nav-text">例：区间变化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E4%BA%8C%E7%BB%B4%E5%8C%BA%E9%97%B4%E4%BF%AE%E6%94%B9"><span class="nav-number">1.2.2.</span> <span class="nav-text">例：二维区间修改</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">CSGrandeur</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">72</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.csgrandeur.cn/2025-04-02-16-%E5%89%8D%E7%BC%80%E5%92%8C%E3%80%81%E5%B7%AE%E5%88%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="CSGrandeur">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="16.前缀和、差分 | CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          16.前缀和、差分
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2025-04-02 11:08:59" itemprop="dateCreated datePublished" datetime="2025-04-02T11:08:59+08:00">2025-04-02</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2025-04-03 18:28:46" itemprop="dateModified" datetime="2025-04-03T18:28:46+08:00">2025-04-03</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/" itemprop="url" rel="index"><span itemprop="name">ACM</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/ACMCOURSE/" itemprop="url" rel="index"><span itemprop="name">ACMCOURSE</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="前缀和差分">前缀和、差分</h1>
<p>前缀和与差分作为互补技术，分别通过预处理和逆运算高效处理数组的区间查询与批量修改问题。</p>
<span id="more"></span>
<h2 id="前缀和">前缀和</h2>
<h3 id="例区间和">例：区间和</h3>
<p>给定 <span class="math inline">\(n\)</span> 个正整数组成的数列 <span
class="math inline">\(a_1,a_2,\cdots,a_n\)</span> 和 <span
class="math inline">\(m\)</span> 个区间 <span
class="math inline">\([l_i,r_i]\)</span>，分别求这 <span
class="math inline">\(m\)</span> 个区间的区间和。</p>
<p>对于所有测试数据，<span class="math inline">\(n,m\leq
10^5\)</span>，<span class="math inline">\(a_i\leq 10^4\)</span></p>
<p>这个问题涉及多次询问，每次都加一遍效率很低。</p>
<p>前缀和是一种简单而强大的预处理技术。它通过预先计算数组中从第一个元素到每个位置的元素之和，使得我们能够在O(1)的时间内求出任意区间的和。</p>
<p>对于一个数组 <span
class="math inline">\(a_1,a_2,\cdots,a_n\)</span>，我们定义前缀和数组
<span class="math inline">\(s_i\)</span> 为:</p>
<p><span class="math inline">\(s_i = \sum_{j=1}^i a_j\)</span></p>
<p>也就是说：</p>
<ul>
<li><span class="math inline">\(s_1 = a_1\)</span></li>
<li><span class="math inline">\(s_2 = a_1 + a_2\)</span></li>
<li><span class="math inline">\(s_3 = a_1 + a_2 + a_3\)</span></li>
<li>...以此类推</li>
</ul>
<p>有了前缀和数组后，要求区间 <span class="math inline">\([l,r]\)</span>
的和，只需要用 <span class="math inline">\(s_r - s_{l-1}\)</span>
即可。这是因为:</p>
<ul>
<li><span class="math inline">\(s_r\)</span> 包含了 <span
class="math inline">\(a_1\)</span> 到 <span
class="math inline">\(a_r\)</span> 的所有元素之和</li>
<li><span class="math inline">\(s_{l-1}\)</span> 包含了 <span
class="math inline">\(a_1\)</span> 到 <span
class="math inline">\(a_{l-1}\)</span> 的所有元素之和</li>
<li>两者相减就得到了 <span class="math inline">\(a_l\)</span> 到 <span
class="math inline">\(a_r\)</span> 的和</li>
</ul>
<p>这样，我们只需要O(n)的时间预处理出前缀和数组，就可以在O(1)的时间内回答任意区间和的询问。对于有大量询问的情况，这种方法比每次都重新计算区间和要高效得多。</p>
<p>例如对于数组 [1,2,3,4,5]:</p>
<ul>
<li>前缀和数组为 [1,3,6,10,15]</li>
<li>要求区间[2,4]的和，只需计算 s[4] - s[1] = 10 - 1 = 9</li>
</ul>
<p>用递推的方式<span
class="math inline">\(O(n)\)</span>就可以得到一个数组的前缀和数组，设数组为<code>a[maxn]</code>，前缀和数组为<code>pre[maxn]</code></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">pre[<span class="number">0</span>] = <span class="number">0</span>;  <span class="comment">// 假设数组数据从下标 1 开始，用 0 作为“哨兵”</span></span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt;= n; i ++) &#123;</span><br><span class="line">    pre[i] = pre[i - <span class="number">1</span>] + a[i];  <span class="comment">// 递推计算前缀和</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>对任意<span
class="math inline">\([i,j]\)</span>（闭区间为例）区间和，<code>pre[j] - pre[i - 1]</code>
可以得到</p>
<h3 id="例最大加权矩形">例：最大加权矩形</h3>
<p>给定一个 <span class="math inline">\(n\times n\)</span>
的矩阵，矩阵中的每个元素都是整数，范围在 <span
class="math inline">\([−127,127]\)</span>
之间。求矩阵中所有可能的矩形中，元素和最大的那个矩形的和。</p>
<p>例如对于矩阵： <figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"> 0 –2 –7  0 </span><br><span class="line"> 9  2 –6  2</span><br><span class="line">-4  1 –4  1 </span><br><span class="line">-1  8  0 –2</span><br></pre></td></tr></table></figure></p>
<p>左下角的 <span class="math inline">\(3\times 2\)</span> 矩形：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">9  2</span><br><span class="line">-4  1</span><br><span class="line">-1  8</span><br></pre></td></tr></table></figure>
<p>和为 15。</p>
<p>先考虑最直观的思路，枚举所有矩形的“左上点”和“右下点”，就算提前计算了所有点的“左上方”的和，至少也是
<span class="math inline">\(O(n^4)\)</span> 的复杂度了。</p>
<p>在复杂度理论中已了解过最大连续和的<span
class="math inline">\(O(n)\)</span>解法，假设最大矩形是 左上点<span
class="math inline">\((r_{1},c_{1})\)</span>，右下点 <span
class="math inline">\((r_{2},c_{2})\)</span>之间的矩形，如果把矩阵其它行都去掉，只保留<span
class="math inline">\([r_{1},r_{2}]\)</span>
这些行，把每一列的和看作一个整体，就能得到一个 <span
class="math inline">\(n\)</span>
元素序列，这个序列的最大连续和，就是<span
class="math inline">\((r_{1},c_{1}),
(r_{2},c_{2})\)</span>这个矩形的和。</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">..........</span><br><span class="line">..........</span><br><span class="line">##@@@@#### ┐</span><br><span class="line">##@@@@####  &gt; 这些行的每一列的和看作一个元素（一列#相加），求最大连续和（@那些列）</span><br><span class="line">##@@@@#### ┘</span><br><span class="line">..........</span><br></pre></td></tr></table></figure>
<p>对于任意行起点<span class="math inline">\(r_{1}\)</span>、行终点<span
class="math inline">\(r_{2}\)</span>，只要能快速得到这些行的各列之和，就能<span
class="math inline">\(O(n)\)</span>求它的最大连续和。</p>
<p>预处理每一列的前缀和（<span
class="math inline">\(O(n^2)\)</span>），这一列的任意起点到终点的和就能立刻得到，枚举行起点（<span
class="math inline">\(O(n)\)</span>）和行终点（<span
class="math inline">\(O(n)\)</span>）以及计算这些行的最大连续和（<span
class="math inline">\(O(n)\)</span>），取最大就是最大矩形了，这个方案的复杂度是<span
class="math inline">\(n^2+n^3=O(n^3)\)</span>。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxn = <span class="number">211</span>;</span><br><span class="line"><span class="comment">// 预处理每一列的前缀和</span></span><br><span class="line"><span class="type">int</span> n, a[maxn][maxn];</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;n);</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i ++) &#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">0</span>; j &lt; n; j ++) &#123;</span><br><span class="line">            <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;a[i][j]);</span><br><span class="line">            a[i][j] += i == <span class="number">0</span> ? <span class="number">0</span> :a[i - <span class="number">1</span>][j]; <span class="comment">// 原地保存列方向前缀和</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> ans = a[<span class="number">0</span>][<span class="number">0</span>];</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> r1 = <span class="number">0</span>; r1 &lt; n; r1 ++) &#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="type">int</span> r2 = r1; r2 &lt; n; r2 ++) &#123;</span><br><span class="line">            <span class="type">int</span> pre = <span class="number">0</span>;</span><br><span class="line">            <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; n; i ++) &#123;</span><br><span class="line">                pre += a[r2][i] - (r1 == <span class="number">0</span> ? <span class="number">0</span> : a[r1 - <span class="number">1</span>][i]); <span class="comment">// 列方向[r1,r2]这一段的和作为一个元素</span></span><br><span class="line">                ans = std::<span class="built_in">max</span>(ans, pre);</span><br><span class="line">                <span class="keyword">if</span>(pre &lt; <span class="number">0</span>) &#123;</span><br><span class="line">                    pre = <span class="number">0</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, ans);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h2 id="差分">差分</h2>
<p>差分是前缀和的逆运算。对于一个数组 <span
class="math inline">\(a\)</span>，它的差分数组 <span
class="math inline">\(b\)</span> 定义为：</p>
<ul>
<li><span class="math inline">\(b_1 = a_1\)</span></li>
<li><span class="math inline">\(b_i = a_i - a_{i-1}\)</span> <span
class="math inline">\((i&gt;1)\)</span></li>
</ul>
<p>容易发现，原数组的任意一个元素都可以通过差分数组的前缀和还原：</p>
<p><span class="math inline">\(a_i = \sum\limits_{j=1}^i
b_j\)</span></p>
<p>差分的一个重要性质是：如果要对原数组的一个区间 <span
class="math inline">\([l,r]\)</span> 同时加上一个数 <span
class="math inline">\(x\)</span>，只需要：</p>
<ul>
<li>令 <span class="math inline">\(b_l\)</span> 加上 <span
class="math inline">\(x\)</span>：因为<span
class="math inline">\(a_{l}\)</span>加了<span
class="math inline">\(x\)</span>而<span
class="math inline">\(a_{l-1}\)</span>没加，<span
class="math inline">\(b_{l}=a_{l}-a_{l-1}\)</span>所以加<span
class="math inline">\(x\)</span>；</li>
<li><span class="math inline">\(b_{l+1}\sim b_{r}\)</span>
不变，因为<span class="math inline">\(a_{l}\sim a_{r}\)</span> 都加了
<span class="math inline">\(x\)</span>，它们相邻的差不变；</li>
<li>令 <span class="math inline">\(b_{r+1}\)</span> 减去 <span
class="math inline">\(x\)</span> （如果 <span
class="math inline">\(r+1\)</span> 存在的话），因为<span
class="math inline">\(a_{r+1}\)</span>没有加<span
class="math inline">\(x\)</span></li>
<li>后面的不变</li>
</ul>
<p>也即<strong>原数在一个区间同时加一个数，差分数组只需要改变区间首尾两个数</strong>。</p>
<h3 id="例区间变化">例：区间变化</h3>
<p>给定一个长度为 <span class="math inline">\(n\)</span> 的数组 <span
class="math inline">\(a\)</span>，有 <span
class="math inline">\(p\)</span> 次操作，每次操作给定三个数 <span
class="math inline">\(x\)</span>、<span
class="math inline">\(y\)</span>、<span
class="math inline">\(z\)</span>，表示将数组 <span
class="math inline">\(a\)</span> 中从第 <span
class="math inline">\(x\)</span> 个到第 <span
class="math inline">\(y\)</span> 个元素（包括这两个位置）都加上 <span
class="math inline">\(z\)</span>。最后求整个数组中的最小值。</p>
<p>模拟这个过程复杂度会很高，如果能把区间修改问题转换为单点修改问题，就会快很多。</p>
<p>参考代码</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="type">const</span> <span class="type">int</span> maxn = <span class="number">5e6</span> + <span class="number">10</span>;</span><br><span class="line"><span class="type">int</span> n, p, a[maxn], l, r, x;</span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d%d&quot;</span>, &amp;n, &amp;p);</span><br><span class="line">    a[<span class="number">0</span>] = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span> (<span class="type">int</span> i = <span class="number">1</span>; i &lt;= n; i++) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;a[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = n; i &gt;= <span class="number">1</span>; i --) &#123;</span><br><span class="line">        <span class="comment">// 原地计算差分，for循环逆序是避免要用的值被先覆盖</span></span><br><span class="line">        a[i] -= a[i - <span class="number">1</span>];   </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">while</span>(p --) &#123;</span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d%d%d&quot;</span>, &amp;l, &amp;r, &amp;x);</span><br><span class="line">        a[l] += x;</span><br><span class="line">        <span class="keyword">if</span>(r + <span class="number">1</span> &lt;= n) &#123;</span><br><span class="line">            a[r + <span class="number">1</span>] -= x;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> ans = a[<span class="number">1</span>];</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">1</span>; i &lt;= n; i ++) &#123;</span><br><span class="line">        a[i] += a[i - <span class="number">1</span>];</span><br><span class="line">        ans = std::<span class="built_in">min</span>(ans, a[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, ans);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="例二维区间修改">例：二维区间修改</h3>
<p>给定一个 <span class="math inline">\(n\times n\)</span> 的网格，有
<span class="math inline">\(m\)</span>
次操作，每次操作给定四个数，表示将左上角为 <span
class="math inline">\((r_1,c_1)\)</span>，右下角为 <span
class="math inline">\((r_2,c_2)\)</span> 的矩形区域内的每个格子都加
<span
class="math inline">\(1\)</span>。最后输出每个格子被加了多少次。</p>
<p>数据范围 <span class="math inline">\(n,m \leq 1000\)</span></p>
<p>根据题目给的数据范围，这道题可以想简单点，对于每个 左上 <span
class="math inline">\((r_1,c_1)\)</span>、右下 <span
class="math inline">\((r_2,c_2)\)</span> 的矩形，都可以看作 <span
class="math inline">\(r_{1}\sim r_{2}\)</span>
这些行分别进行一次区间增长，分别用差分来单点更新：</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">0  0  0  0  0  0</span><br><span class="line">0 +1  0  0  0 -1</span><br><span class="line">0 +1  0  0  0 -1</span><br><span class="line">0 +1  0  0  0 -1</span><br><span class="line">0 +1  0  0  0 -1</span><br><span class="line">0  0  0  0  0  0</span><br></pre></td></tr></table></figure>
<p>复杂度分析：初始化计算每一行差分数组，<span
class="math inline">\(O(n^2)\)</span>，<span
class="math inline">\(m\)</span> 个操作、每个操作最坏对 <span
class="math inline">\(n\)</span> 行的差分数组做 <span
class="math inline">\(O(1)\)</span> 操作，总复杂度 <span
class="math inline">\(n^{2}+mn=O(mn)\)</span>，<span
class="math inline">\(n,m \leq 1000\)</span>，复杂度可接受。</p>
<p>更多思考：一些同学可能想到两次差分，把多行多次差分数组更新变成首尾两次：</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">0  0  0  0  0  0</span><br><span class="line">0 +1  0  0  0 -1</span><br><span class="line">0  0  0  0  0  0</span><br><span class="line">0  0  0  0  0  0</span><br><span class="line">0  0  0  0  0  0</span><br><span class="line">0 -1  0  0  0 +1</span><br></pre></td></tr></table></figure>
<p>而这道题<span class="math inline">\(m\)</span>和<span
class="math inline">\(n\)</span>范围一致，即使把 <span
class="math inline">\(O(mn)\)</span> 优化到 <span
class="math inline">\(O(m)\)</span>，初始差分表也有个 <span
class="math inline">\(O(n^2)\)</span> 在，<span
class="math inline">\(n^{2}+m=O(n^2)\)</span>
，复杂度没有本质提升。不过如果 <span class="math inline">\(m\)</span> 比
<span class="math inline">\(n\)</span>
大很多，那么这个优化还是有意义的，可以尝试。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/ACM/" rel="tag"># ACM</a>
              <a href="/tags/Algorithm/" rel="tag"># Algorithm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2025-03-27-15-%E5%A4%8D%E6%9D%82%E5%BA%A6%E7%90%86%E8%AE%BA%E4%B8%8E%E5%88%86%E6%B2%BB/" rel="prev" title="15.复杂度理论与分治">
                  <i class="fa fa-angle-left"></i> 15.复杂度理论与分治
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2025-04-02-17-%E8%B4%AA%E5%BF%83/" rel="next" title="17.贪心">
                  17.贪心 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">CSGrandeur</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://fastly.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://fastly.jsdelivr.net/npm/@next-theme/pjax@0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://fastly.jsdelivr.net/npm/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>







  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://fastly.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"CSGrandeur/csgrandeur.github.io","issue_term":"pathname","theme":"github-light"}</script>
<script src="/js/third-party/comments/utterances.js"></script>

</body>
</html>
